package demo3;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-03
 * Time: 16:41
 */
public class MyBlockingQueue {
    private int[] elem;//数组

    private int rear;//队尾
    private int front;//对头
    private int usedSize;
    public MyBlockingQueue(){
        this.elem = new int[1000];
        this.rear = 0;
        this.front = 0;
        this.usedSize =0 ;
    }

    public void put(int val) throws InterruptedException {
        synchronized(this){
            while(this.usedSize==this.elem.length){
                this.wait();
            }
            this.elem[this.rear] = val;
            this.rear++;
            if(this.rear==this.elem.length){
                this.rear = 0;
            }
            this.usedSize++;
            this.notify();
        }
    }

    public Integer take() throws InterruptedException {
        int ret = 0;
        synchronized(this){
            while(this.usedSize==0){
                this.wait();
            }
            ret = this.elem[this.front];
            this.front++;
            if(this.front==this.elem.length){
                this.front = 0;
            }
            this.usedSize--;
            this.notify();
        }
        return ret;
    }

    public static void main(String[] args) {
        //生产者消费者模型--演示
        MyBlockingQueue queue = new MyBlockingQueue();
        //消费者
        Thread customer = new Thread(()->{
            while(true){
                try {
                    int x = queue.take();
                    System.out.println("消费者-消费了 : "+ x);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
        //生产者
        Thread producer = new Thread(()->{
            int n = 0;
            while(true){
                try {
                    queue.put(n);
                    System.out.println("生产者-生产了 :" + n);
                    n++;

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
    }
}
